$(function () {
    function reset_token() {
        // 获取token
        $.post("/api/auth/login", {'username': "zmd_gps_admin", 'password': 'p@ssw0rd'}, function (res) {
           $("#tyibs_api_token").val(res.data.token);
        });
    }
    reset_token();

    var lift_gps_address = $("#tyibs_lift_gps_address").val();
    var maintenance_company_id = $("#tyibs_lift_main_company_id").val();
    var lift_icon = new BMap.Icon("/er/static/src/img/warning.gif",new BMap.Size(80,80));
    var move_car_icon = new BMap.Icon("/lift_base/static/src/img/move_car.png", new BMap.Size(25, 50),{imageSize:new BMap.Size(25,50)});
    var stop_car_icon = new BMap.Icon('/lift_base/static/src/img/stop_car.png', new BMap.Size(25, 50),{imageSize:new BMap.Size(25,50)});
    var main_company_icon = new BMap.Icon("/lift_base/static/src/img/maintenance_company.png", new BMap.Size(32, 32));
    var save_company_icon = new BMap.Icon("/lift_base/static/src/img/salvager_unit.png", new BMap.Size(32, 32));
    var map = new BMap.Map("tyibs-save-map");
    map.enableScrollWheelZoom(true);
    var car_overlay = [];
    var lift_point = "";

    //显示维保公司和二级救援单位
    show_all_save_company();

    function set_marker(lng, lat) {
        //设置电梯的marker
        lift_point = new BMap.Point(lng, lat);
        map.centerAndZoom(lift_point, 12);
        lift_marker = new BMap.Marker(lift_point, {icon: lift_icon});
        map.addOverlay(lift_marker);
        lift_marker.addEventListener('click', function (e) {
            var info_window_html = '<div class="tyibs-map-info-window">'
                                    + '<h4>' + $("#tyibs_lift_code").val() + '</h4>'
                                    + '<span>设备注册代码：' + $("#tyibs_lift_register_code").val() + '</span>'
                                    + '<br/><span>设备类别：' + $("#tyibs_lift_big_category").val() + '</span>'
                                    +' <br/><span>使用单位：'+ $("#tyibs_lift_use_company").val() +'</span>'
                                    + '<br/><span>维保单位：'+ $("#tyibs_lift_main_company").val() +'</span>'
                                    + '<br/><span>维保公司站点：' + $("#tyibs_lift_maintenance_site").val() + '</span>'
                                    + '<br/><span>维保公司救援人员：' + $("#tyibs_lift_maintenance_salvager").val() + '</span>'
                                    + '<br/><span>维保公司救援人员电话：' + $("#tyibs_lift_maintenance_salvager_mobile").val() + '</span>'
                                    +'</div>';
            var info_window = new BMap.InfoWindow(info_window_html);
            map.openInfoWindow(info_window,lift_point);
        });

        var convertor = new BMap.Convertor();
        $.get("/er/client/map/get/all/cars", function (res_cars) {
            res_cars = JSON.parse(res_cars);
            show_all_car(convertor,res_cars);
            setInterval(function(){show_all_car(convertor,res_cars)}, 1000 * 5);
        });
    }

    var show_all_car = function (convertor,cars) {
        // 显示所有车辆
        if ($("#tyibs_api_token").val() == ""){
            reset_token();
        }
        $.ajax({
            async: true,
            url: '/api/device/gps/current',
            type: 'POST',
            headers: {
                'x-access-token': $("#tyibs_api_token").val()
            },
            success: function (cars_gps_data) {
                if (cars_gps_data.code == 0 && cars_gps_data.data.length > 0){
                    cars.forEach(function (car) {
                        var car_gps = cars_gps_data.data.filter(function (item) {
                            return car.device_code == item.device_code;
                        });
                        if (car_gps.length >0){
                            convertor.translate([new BMap.Point(car_gps[0].position.lng, car_gps[0].position.lat)], 1, 5, function (data) {
                                if(data.status === 0) {
                                    var exist_marker = car_overlay.filter(function (marker) {
                                        return marker.device_code == car_gps[0].device_code;
                                    });
                                    var compute_time_and_space = new BMap.DrivingRoute(map, {renderOptions: {},
                                        onSearchComplete: function (results){
                                            if (compute_time_and_space.getStatus() != BMAP_STATUS_SUCCESS){
                                                return ;
                                            }
                                            var plan = results.getPlan(0);
                                            //获取时间
                                            var need_time = plan.getDuration(true);
                                            //获取距离
                                            var need_space = plan.getDistance(true);
                                            $("#time_" + car_gps[0].device_code).html(need_time);
                                            $("#space_" + car_gps[0].device_code).html(need_space);
                                        }
                                    });
                                    compute_time_and_space.search(data.points[0], lift_point);
                                    if (exist_marker.length > 0){
                                        // marker已存在，更改其position
                                        exist_marker[0].setPosition(data.points[0]);
                                        set_car_state(exist_marker[0]);
                                        $("#state_" + car_gps[0].device_code).html(car_gps[0].position.state);
                                        $("#address_" + car_gps[0].device_code).html(car_gps[0].position.address);
                                        $("#speed_" + car_gps[0].device_code).html(car_gps[0].position.speed);
                                    }else {
                                        // marker不存在，创建marker
                                        var marker = new BMap.Marker(data.points[0]);
                                        var marker_label = new BMap.Label(car.code + "-" + car.manager, {offset   : new BMap.Size(-35, -20)});
                                        marker_label.setStyle({
                                             color : "red"
                                         });
                                        marker.setLabel(marker_label);
                                        marker.device_code = car_gps[0].device_code;
                                        marker.addEventListener('click', function (e) {
                                            set_info_window(car_gps[0].device_code,car_gps[0].position.state,car_gps[0].position.address,car_gps[0].position.speed,marker);
                                        });
                                        set_car_state(marker);
                                        map.addOverlay(marker);
                                        car_overlay.push(marker);
                                    }
                                    function set_car_state(marker) {
                                        // 修改小车车的icon
                                        if (car_gps[0].position.speed > 0){
                                            //车子在动
                                            marker.setIcon(move_car_icon);
                                        }else {
                                            //车子静止
                                            marker.setIcon(stop_car_icon);
                                        }
                                        //改变小车车方向
                                        marker.setRotation(car_gps[0].position.direction);
                                    }
                                }
                            });
                        }
                    })

                }
            }
        });
    }

    var set_info_window = function (device_code,state,current_address,speed,marker) {
        //设置救援车辆的infowindow
        $.get("/er/client/map/dispatch/car/" + device_code, function (res) {
            res = JSON.parse(res);
            var car_type = "前往救援";
            if ($("#tyibs_save_car_id").val() == res.car_id){
                car_type = "正在救援";
            }
            var info_window_html = '<div class="tyibs-map-info-window">'
                                    + '<h4>' + res.enterprise_name + '</h4><span>车牌号码：'+ res.code +'</span>'
                                    + '<br/><span>GPS编码：' + device_code + '</span>'
                                    + '<br/><span>车载电话：'+ res.GPS_mobile +'</span><br/><span>车辆负责人：' + res.manager + '</span>'
                                    + '<br/><span>负责人电话：' + res.manager_mobile + '</span>'
                                    + '<br/>当前位置：<span id="address_' + device_code + '">' + current_address + '</span>'
                                    + '<br/>车辆状态：<span id="state_' + device_code + '">'+ state +'</span>'
                                    + '<br/>当前车速：<span id="speed_' + device_code + '">' + speed + '</span>km/h'
                                    + '<br/><span>距离事故电梯：<span id="space_' + device_code + '">获取中...</span></span><br/>'
                                    + '<span>所需时间：<span id="time_' + device_code + '">获取中...</span></span></div>';
            var infoWindow = new BMap.InfoWindow(info_window_html);
            infoWindow.addEventListener('open', function () {

                var compute_time_and_space = new BMap.DrivingRoute(map, {renderOptions: {},
                    onSearchComplete: function (results){
                        if (compute_time_and_space.getStatus() != BMAP_STATUS_SUCCESS){
                            return ;
                        }
                        var plan = results.getPlan(0);
                        //获取时间
                        var need_time = plan.getDuration(true);
                        //获取距离
                        var need_space = plan.getDistance(true);
                        $("#time_" + device_code).html(need_time);
                        $("#space_" + device_code).html(need_space);
                    }
                });
                compute_time_and_space.search(marker.getPosition(), lift_point);

                // 绑定点击事件一定要在这里绑定
                // $(".tyibs_save_btn").click(function () {
                //     var $this = $(this);
                //     $.post("/er/client/map/dispatch/save/order/" + $("#tyibs_save_order_id").val() + "/set/car", {car_id: $this.attr("data-car-id")}, function (res) {
                //         res = JSON.parse(res);
                //         if (res.error_code == 0){
                //             $(".tyibs_save_btn").text("前往救援");
                //             $this.text("正在救援");
                //             $this.attr("disabled", "disabled");
                //             $("#tyibs_save_car_id").val($this.attr("data-car-id"));
                //             $("#tyibs_save_car_device_code").val($this.attr("data-device-code"));
                //         }else {
                //             $this.text(res.error_msg);
                //             $this.attr("disabled", "disabled")
                //         }
                //     })
                // })
            });
            marker.openInfoWindow(infoWindow);
        });
    };

    // 先将电梯的导航地址转换为坐标，设置一个marker
    if (lift_gps_address == ""){
        set_marker($("#tyibs_lift_lng").val(), $("#tyibs_lift_lat").val());
    }else {
        $.ajax({
            url:"http://api.map.baidu.com/geocoder/v2/?address=" + lift_gps_address +"&output=json&ak=XYeVsCzcw7Rz0cCt3ZnZtBD2ohUTlMXX&callback=showLocation",
            dataType:'jsonp',
            data:'',
            jsonp:'callback',
            success:function(gps_result) {
                set_marker(gps_result.result.location.lng, gps_result.result.location.lat);
            },
            error:function(){
                alert("无法获取到位置。")
            }
        });
    }

    function show_all_save_company(){
        //获取所有救援单位，包含电梯本身的维保单位
        $.post("/er/client/map/get/all/save/company", {maintenance_id: maintenance_company_id}, function (result) {
            result = JSON.parse(result);
            if (result.length > 0){
                result.forEach(function (item) {
                    set_company_marker(item);
                })
            }
        });
    }

    var set_company_marker = function (company) {
        //设置维保公司和救援单位的marker
        var type = "二级救援单位";
        var point = new BMap.Point(company.lng,company.lat);
        var marker = new BMap.Marker(point);
        if (company.id == maintenance_company_id){
            marker.setIcon(main_company_icon);
            type = "电梯所在维保公司"
        }else {
            marker.setIcon(save_company_icon);
        }
        var label = new BMap.Label(type,{offset   : new BMap.Size(-30, -25)});
        label.setStyle({color : "red"});
        marker.setLabel(label);
        var info_window_html = '<div class="tyibs-map-info-window">'
                                + '<h4>' + company.name + '</h4>'
                                + '<span>性质：'+ type +'</span>'
                                + '<br/><span>地址：'+ company.address +'</span>'
                                + '<br/><span>联系人：'+ company.contact +'</span><br/><span>手机：' + company.mobile + '</span>'
                                + '<br/><span>固定电话：' + company.phone + '</span><br/></div>';
        var infoWindow = new BMap.InfoWindow(info_window_html);

        map.addOverlay(marker);
        marker.addEventListener("click", function () {
            marker.openInfoWindow(infoWindow);
        })
    }

})